package com.ly.mpayment.rest.up.feizhidu;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("feizhidu")
public class FeiZhiDuRest {
    Logger logger = Logger.getLogger(FeiZhiDuRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    /**
     * order_id	string	是 	充值订单号
     * third_id	String	是	商家订单号
     * state	Int	是	订单状态
     *  2 处理中（如不需要可忽略）
     *  8充值失败
     *  9 充值成功
     * time	Int	否	处理时间
     * voucher	String 	否	凭证信息
     * 网厅渠道，返回网厅订单ID，其它渠道为空
     * info	String	否	如充值失败，对应错误信息
     * card_no	String	否	如果我们是卡密充值，那么会返回卡号
     *
     * app_key	string	是 	分配给商户APPKEY
     * timestamp	Int	是 	Unix时间戳,时区为 GMT+8 允许与服务器最大误差30秒
     * sign	String	是 	所有请求参数签名 ，详见签名算法
     * @return
     */
    @Path("callBack")
    @GET
    public String callBack(@QueryParam("order_id")String order_id, @QueryParam("third_id")String third_id, @QueryParam("state")String state
            , @QueryParam("time")String time, @QueryParam("voucher")String voucher, @QueryParam("info")String info
            , @QueryParam("card_no")String card_no , @QueryParam("app_key")String app_key , @QueryParam("timestamp")String timestamp
            , @QueryParam("sign")String sign) {
        //{"third_id":"2c922ab97aaa8d0d017aaa8d6de80004","app_key":"704122410","voucher":"003420210715222356936775","state":"9","time":"1626359046",
        // "order_id":"324292951","info":"","timestamp":"1626399767"}
        logger.info("feizhidu_callback_success:order_id:" + order_id+",third_id:"+third_id+",state:"+state+",time:"+  time+",voucher:"+voucher+",info:"+info+",sign="+sign);
        JSONObject data = new JSONObject();
        if (!StringUtils.isBlank(third_id)) {
            data.put("order_id",order_id);
            data.put("state", state);
            data.put("third_id", third_id);
            data.put("time",time);
            data.put("voucher",voucher);
            data.put("info",info);
            data.put("card_no",card_no);
            data.put("app_key",app_key);
            data.put("timestamp",timestamp);
            //{"third_id":"2c922ab982fd35b40182fd3df021080f","app_key":"704122410","voucher":"7372877537202209024580084725","state":"9","time":"1662106301","order_id":"1029992871","info":"","timestamp":"1662106301"}
            logger.info("feizhidu_callback:"+data);

            UpOrder order = upOrderService.findById(third_id);
            if(order == null){
                logger.info("订单不存在:"+third_id);
                data.clear();
                data.put("ret",1);
                data.put("msg","订单不存在");
                return data.toString();
            }
            final UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
            if(upShopInfo == null){
                logger.info("渠道用户不存在:"+third_id);
                data.clear();
                data.put("ret",1);
                data.put("msg","渠道用户不存在");
                return data.toString();
            }
//            if(!sign.equals(MD5.md5(StringSort.doSignKeyValueNull(data).concat(upShopInfo.getUpkey())))){
//                logger.info("签名错误:"+data);
//                data.clear();
//                data.put("ret",1);
//                data.put("msg","签名错误");
//                //return data.toString();
//            }

            if (order != null && state.equals("9") && order.getStatus() == Config.status[0]) {
                order.setRemark(StringUtils.isBlank(card_no) ? StringUtils.isBlank(voucher) ? info : voucher : card_no);
                RechargeRest.successUpOrder.add(order);
                data.clear();
                data.put("ret",0);
                data.put("msg","");
                return data.toString();
            } else if (order != null && order.getStatus() == Config.status[0] && state.equals("8")) {
                order.setRemark(StringUtils.isBlank(voucher) ? state : info);
                RechargeRest.failtUpOrder.add(order);
                data.clear();
                data.put("ret",0);
                data.put("msg","");
                return data.toString();
            } else {
                this.upOrderService.addOrderMsg(order,state);
                logger.info("feizhidu_not_found_order:" + state + "," + (order == null ? "" : order.getUpphonenum()));
            }
        }
        data.clear();
        data.put("ret",0);
        data.put("msg","");
        return data.toString();
    }

    /**
     * 订单提交
     * 错误码	接口	错误描述
     * 0	所有	成功
     * 1	所有	参数错误
     * 2	所有	签名错误
     * 3	所有	时间戳超期
     * 4	所有	商户不存在
     * 5	所有	商户被禁用
     * 10	充值	第三方订单号已存在（有提交过第三方系统的此笔订单），需以成功提交处理
     * 11	充值	充值金额不正确
     * 12	充值	账户余额不足
     * 13	充值	渠道不可用或无资源
     * 14	充值	充值故障，请稍后再试
     * 15	充值	充值手机号有问题（号码格式错误，空号或已拉黑号）
     * 20	查询	订单不存在
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        data.put("timestamp",(System.currentTimeMillis()/1000L)+"");
        data.put("app_key", shop.getAppId());

        data.put("third_id", order.getUporderuuid());
        data.put("phone", order.getUpphonenum());
        data.put("amount", order.getUpShopPro().getUpfacevalue());

        data.put("sign", MD5.md5(StringSort.doSignKeyValue(data).concat(shop.getUpkey())));

        String result = HttpClient.httpGetUrl(shop.getOrderCommitAddress().concat("?").concat(StringSort.jsonToString(data)));
        logger.info("commitOrder_feizhidu:" + result + ":" + shop.getOrderCommitAddress().concat("?").concat(StringSort.jsonToString(data)));
        //amount=10&app_key=704122410&phone=18782435841&sign=4da1c821b73ed3a1e356f320e7c3d705&third_id=2c922ab97aaa6346017aaa6c11f20008&timestamp=1626356847
        if (!StringUtils.isBlank(result)) {
            try{
                JSONObject json = JSONObject.parseObject(result);
                if (json.containsKey("ret") && json.getString("ret").equals("0")) {
                    this.upOrderService.updateUpOrderMsg(order,json.getJSONObject("data").getString("order_id"),json.containsKey("msg") ?
                            json.getString("msg") : "");
                } else if (json.containsKey("ret") && errorCode.contains(json.getString("ret"))){
                    order.setRemark(json.getString("msg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.addOrderMsg(order, json.getString("msg"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrderArtificial(order, "","人工");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    /**
     * 0	所有	成功
     * 1	所有	参数错误
     * 2	所有	签名错误
     * 3	所有	时间戳超期
     * 4	所有	商户不存在
     * 5	所有	商户被禁用
     * 10	充值	第三方订单号已存在（有提交过第三方系统的此笔订单），需以成功提交处理
     * 11	充值	充值金额不正确
     * 12	充值	账户余额不足
     * 13	充值	渠道不可用或无资源
     * 14	充值	充值故障，请稍后再试
     * 15	充值	充值手机号有问题（号码格式错误，空号或已拉黑号）
     * 20	查询	订单不存在
     */
    Set<String> errorCode = new HashSet<String>(){{
        add("1");
        add("2");
        add("3");
        add("4");
        add("5");
        add("11");
        add("12");
        add("13");
        add("14");
        add("15");
    }};

    /**
     * 订单查询
     *
     * @param order
     * @param shop
     */
    public void queryOrder(UpOrder order, UpShopInfo shop) {
        JSONObject data = new JSONObject();
        data.put("timestamp",(System.currentTimeMillis()/1000L)+"");
        data.put("app_key", shop.getAppId());

        data.put("third_id", order.getUporderuuid());
        data.put("sign", MD5.md5(StringSort.doSignKeyValue(data).concat(shop.getUpkey())));


        String result = HttpClient.httpGetUrl(shop.getOrderStatusAddress().concat("?").concat(StringSort.jsonToString(data)));
        logger.info("feizhiduqueryOrder:" + shop.getOrderStatusAddress().concat("?").concat(StringSort.jsonToString(data)) + ":" + result);
        if (!StringUtils.isBlank(result)) {
            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("ret") && json.getString("ret").equals("0")) {
                JSONObject item = json.getJSONObject("data");
                UpOrder upOrder = upOrderService.findById(item.getString("third_id"));
                if (order != null && item.getString("state").equals("9") && order.getStatus() == Config.status[0]) {
                    order.setRemark( item.containsKey("voucher") ? item.getString("voucher") :
                            item.getString("info"));
                    RechargeRest.successUpOrder.add(order);
                } else if (order != null && order.getStatus() == Config.status[0] && item.getString("state").equals("8") ) {
                    order.setRemark(item.getString("info"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    this.upOrderService.addOrderMsg(order,item.getString("resultno"));
                    logger.info("feizhidu_not_found_order:" + order.getUpphonenum());
                }
            } else {
                logger.info("feizhidu_not_found_order:" + order.getUpphonenum());
            }
        }
    }

}
